package com.wealth.scsj.p_app.view.activity.loginmodel;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.vondear.rxtools.RxDataTool;
import com.wealth.scsj.p_app.R;
import com.wealth.scsj.p_app.utils.SkipUtils;
import com.wealth.scsj.p_app.view.activity.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import es.dmoral.toasty.Toasty;
import okhttp3.internal.platform.Platform;

/**
 * 密码登录界面
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {


    private ImageView mTopIv;
    private ImageView mRegisterCancelBtn;
    /**
     * 登录
     */
    private Button mLoginTypeBtn;
    /**
     * 短信登录
     */
    private Button mMsgLoginTypeBtn;
    private RelativeLayout mTopLayout;
    /**  */
    private EditText mPhoneEt1;
    /**  */
    private EditText mPswEt;
    /**  */
    private EditText mCodeEt;
    /**
     * 发送验证码
     */
    private Button mSendLoginCodeBtn;
    /**
     * <u>登录</u>
     */
    private Button mLoginBtn;
    /**
     * 立即注册
     */
    private TextView mRegisterTv;
    /**
     * 忘记密码
     */
    private TextView mForgetPswTv;
    private ImageView mWxLoginIv;
    private ImageView mQqLoginIv;
    private LinearLayout mLoginLayout;
    private String mSPhoneEt1;
    private String mSPswEt;
    private int loginType = 1;//1代表普通登录  2代表短信登录

    private boolean isClick = false;
    private String thirdType = "";
    private Platform platform;
    private String openId = "";
    private String clentId = "";
//    public Dialog loadingDialog;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 101:
//                    if (loadingDialog != null && !isFinishing())
//                        loadingDialog.show();
                    platform = (Platform) msg.obj;
                   // getUnionid(platform.getDb().getToken());
//                    thirdType = "qq";
//                    goLoginByThird(platform.getDb().getUserId().toString(), "user_qqopenid");
                    break;
                case 102:
//                    if (loadingDialog != null && !isFinishing())
//                        loadingDialog.show();
                    platform = (Platform) msg.obj;
                    thirdType = "wx";
                    ///isExistUnionId(platform.getDb().getUserId().toString(), "user_wxopenid");
                    break;
                case 103:
                case 104:
                    Toasty.normal(LoginActivity.this, "目前您的微信版本过低或未安装微信，需要安装微信才能使用").show();
                    isClick = false;
                    break;
            }
            super.handleMessage(msg);
        }
    };


    @Override
    protected void createView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);
        initView();
    }

    @Override
    protected void initView() {


        mTopIv = (ImageView) findViewById(R.id.top_iv);
        mRegisterCancelBtn = (ImageView) findViewById(R.id.register_cancel_btn);
        mRegisterCancelBtn.setOnClickListener(this);
        mLoginTypeBtn = (Button) findViewById(R.id.login_type_btn);
        mLoginTypeBtn.setOnClickListener(this);
        mMsgLoginTypeBtn = (Button) findViewById(R.id.msg_login_type_btn);
        mMsgLoginTypeBtn.setOnClickListener(this);
        mTopLayout = (RelativeLayout) findViewById(R.id.top_layout);
        mPhoneEt1 = (EditText) findViewById(R.id.phone_et_1);
        mPswEt = (EditText) findViewById(R.id.psw_et);
        mCodeEt = (EditText) findViewById(R.id.code_et);
        mSendLoginCodeBtn = (Button) findViewById(R.id.send_login_code_btn);
        mSendLoginCodeBtn.setOnClickListener(this);
        mLoginBtn = (Button) findViewById(R.id.login_btn);
        mLoginBtn.setOnClickListener(this);
        mRegisterTv = (TextView) findViewById(R.id.register_tv);
        mRegisterTv.setOnClickListener(this);
        mForgetPswTv = (TextView) findViewById(R.id.forget_psw_tv);
        mForgetPswTv.setOnClickListener(this);
        mWxLoginIv = (ImageView) findViewById(R.id.wx_login_iv);
        mWxLoginIv.setOnClickListener(this);
        mQqLoginIv = (ImageView) findViewById(R.id.qq_login_iv);
        mLoginLayout = (LinearLayout) findViewById(R.id.login_layout);
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {
////        loginbtn.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
////        login_phone_tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
////        login_pwd_tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
//     //   RxTextTool.getBuilder("").setBold().setAlign(Layout.Alignment.ALIGN_CENTER).append("登录即表示您已认同益联益家隐私政策")..into(loginprivatetv);
//        //创建一个 SpannableString对象
////        msp = new SpannableString("登录即表示您已认同益联益家隐私政策");
////        msp.setSpan(new UnderlineSpan(), 9, 17, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
////        msp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 9, 17, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
////        loginprivatetv.setText(msp);
////        loginprivatetv.setMovementMethod(LinkMovementMethod.getInstance());
////        loginpwdet.setTransformationMethod(PasswordTransformationMethod.getInstance());
////
////        loginnumet.setOnEditorActionListener(new TextView.OnEditorActionListener() {
////
////            @Override
////            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
////                Log.e("输入完点击确认执行该方法", "输入结束");
////                return false;
////            }
////        });
//
//
//        loginpwdet.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//                if (!RxDataTool.isEmpty(charSequence)) {
//                    loginprivateiv2.setVisibility(View.VISIBLE);
//                } else {
//                    loginprivateiv2.setVisibility(View.GONE);
//                }
//            }
//
//            @Override
//            public void afterTextChanged(Editable editable) {
//                boolean isVisible = editable.length() >= 1;
//                if (isVisible) {
//                    loginprivateiv2.setVisibility(View.VISIBLE);
//                } else {
//                    loginprivateiv2.setVisibility(View.GONE);
//                }
//            }
//        });
//
//        loginpwdet.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                Log.e("输入完点击确认执行该方法", "输入结束");
//                return false;
//            }
//        });
//
//
//        loginprivateiv2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//                if (b) {
//                    //显示密码
//                    loginpwdet.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
//                } else {
//                    //隐藏密码
//                    loginpwdet.setTransformationMethod(PasswordTransformationMethod.getInstance());
//                }
//            }
//        });


    }

    @Override
    public void finish() {
        // TODO Auto-generated method stub
        super.finish();
        //关闭窗体动画显示
        this.overridePendingTransition(0, R.anim.login_close);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_type_btn:
                //普通登录
                if (loginType == 2) {
                    mPswEt.setVisibility(View.VISIBLE);
                    mCodeEt.setVisibility(View.GONE);
                    mSendLoginCodeBtn.setVisibility(View.GONE);

                    loginType = 1;
                }

                break;
            case R.id.msg_login_type_btn:
                //短信登录
                if (loginType == 1) {
                    mPswEt.setVisibility(View.GONE);
                    mCodeEt.setVisibility(View.VISIBLE);
                    mSendLoginCodeBtn.setVisibility(View.VISIBLE);
                    loginType = 2;
                }

                break;
            case R.id.register_cancel_btn://关闭
                closeKeyboard();
                finish();
                break;
            case R.id.register_tv:
                //注册
                SkipUtils.toRegisterPage(this);
                break;
            case R.id.forget_psw_tv:
                //忘记密码
                SkipUtils.toForgetPswdPage(this);
                break;

            case R.id.login_btn://登录

                mSPhoneEt1 = mPhoneEt1.getText().toString().trim();
                mSPswEt = mPswEt.getText().toString().trim();

                if (!(RxDataTool.isEmpty(mSPhoneEt1)) && !(RxDataTool.isEmpty(mSPswEt))) {
//                    MineFragment.isLogin = 1;
                    closeKeyboard();
//                    Logger.d(mSPhoneEt1 + "  " + mSPswEt);


                } else {
                    Toasty.error(this, "请完善账号信息").show();
                }
            case R.id.send_login_code_btn://发送验证码
                break;

            case R.id.wx_login_iv:
                break;
        }

    }

    private void WEIXINLogin() {

        finish();
        if (isClick) {
            Toasty.normal(this, "您已经点过了，请稍后").show();
            return;
        }

        isClick = true;

//        Platform weibo = ShareSDK.getPlatform(Wechat.NAME);
//        if (weibo.isAuthValid()) {
//            weibo.removeAccount(true);
//        }
//
//        weibo.SSOSetting(false);  //设置false表示使用SSO授权方式
//
//        weibo.setPlatformActionListener(new PlatformActionListener() {
//            @Override
//            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//                Logger.e("here is third Login==>" + hashMap.toString());
//                thirdType = "wx";
//
//                isExistUnionId(hashMap.get("unionid").toString(), "user_wxopenid");
//            }
//
//            @Override
//            public void onError(Platform platform, int i, Throwable throwable) {
//                Logger.e("here is third Login11111==>" + i);
//                if (throwable instanceof WechatClientNotExistException) {
//                    handler.sendEmptyMessage(103);
//                } else if (throwable instanceof WechatTimelineNotSupportedException) {
//                    handler.sendEmptyMessage(104);
//                }
//            }
//
//            @Override
//            public void onCancel(Platform platform, int i) {
//                Logger.e("here is third Login cancel==>");
//                Toasty.info(LoginActivity.this, "微信登录已取消").show();
//                isClick = false;
//            }
//        }); // 设置分享事件回调
//        weibo.authorize();//单独授权
//        weibo.showUser(null);
    }

    /**
     * 确认该unionId是否存在数据库
     */
    private void isExistUnionId(final String openId, final String type) {
//        if (!HttpUtil.isNetworkConnected(this)) {
//            Tool.goNoNetWork(context);
//            return;
//        }

        // TODO: 2018/7/17 下边这句暂时注释
//        clentId = jpushid;

        JSONObject ob = new JSONObject();
        try {
            ob.put("openId", openId);
            ob.put("type", type);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String data = ob.toString();
        // TODO: 2018/7/17 下边的联网方法暂时注释掉
//        NetWorkUtils.postHttpRequest(Tool.getParams(data, LoginActivity.this, Constants.THIRD_LOGIN_CHECK),
//                new NetWorkUtils.HttpCallback() {
//                    @Override
//                    public void onSuccess(String result) {
//                        MyLog.e(TAG, "请求成功666000777" + result);
//                        BaseBean bean = BaseBean.praseJSONObject(result);
//                        if (bean != null) {
//                            if (bean.getRet() == 1) {
//                                try {
//                                    String phone = "";
//                                    String id = "";
//                                    JSONObject ob = new JSONObject(bean.getData());
//                                    if (ob.has("phone")) {
//                                        phone = ob.getString("phone");
//                                    }
//                                    if (ob.has("id")) {
//                                        id = ob.getString("id");
//                                    }
//                                    if (!TextUtils.isEmpty(id)) {
//                                        if (TextUtils.isEmpty(phone)) {
//                                            Intent intent = new Intent(LoginActivity.this, ThirdLoginSetPhoneActivity.class);
//                                            intent.putExtra("isFrist", false);
//                                            intent.putExtra("openId", openId);
//                                            intent.putExtra("type", type);
//                                            intent.putExtra("clentId", clentId);
//                                            startActivityForResult(intent, 101);
//                                        } else {
//                                            goLoginByThird(openId, type);
//                                        }
//                                    } else {
//                                        Intent intent = new Intent(LoginActivity.this, ThirdLoginSetPhoneActivity.class);
//                                        intent.putExtra("isFrist", true);
//                                        intent.putExtra("openId", openId);
//                                        intent.putExtra("type", type);
//                                        intent.putExtra("clentId", clentId);
//                                        startActivity(intent);
//                                    }
//                                } catch (JSONException e) {
//                                    e.printStackTrace();
//                                }
//                            } else {
//                                showToast(bean.getMsg());
//                            }
//
//                        } else {
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable ex, boolean isOnCallback) {
//                        MyLog.e(TAG, "http请求失败：" + ex.toString());
//                        dialogDismiss();
//                    }
//
//                    @Override
//                    public void onCancelled(Callback.CancelledException cex) {
//                        dialogDismiss();
//                    }
//
//                    @Override
//                    public void onFinished() {
//                        dialogDismiss();
//                    }
//                });
    }


    /**
     * 第三方登录
     *
     * @param openId
     * @param type
     */
    private void goLoginByThird(final String openId, final String type) {
        this.openId = openId;
//        if (!HttpUtil.isNetworkConnected(this)) {
//            Tool.goNoNetWork(context);
//            return;
//        }

        // TODO: 2018/7/17 下边这句暂时注释掉
//        clentId = jpushid;

        JSONObject ob = new JSONObject();
        try {
            ob.put("openId", openId);
            ob.put("type", type);
            ob.put("clientId", clentId);
            ob.put("userLoginIp", "192.168.0.1");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // TODO: 2018/7/18 下边的联网先注释掉
//        String data = ob.toString();
//        String paramString = Tool.getParams(data, LoginActivity.this, Constants.THREE_LOGIN).toString();
//        NetWorkUtils.postHttpRequest(Tool.getParams(data, LoginActivity.this, Constants.THREE_LOGIN),
//                new NetWorkUtils.HttpCallback() {
//                    @Override
//                    public void onSuccess(String result) {
//                        MyLog.d(TAG, "请求成功" + result);
//                        BaseBean bean = BaseBean.praseJSONObject(result);
//                        if (bean != null) {
//                            if (bean.getRet() == 1) {
////                        doPrise(bean.getData());
//                                User userBean = new Gson().fromJson(bean.getData(), User.class);
//                                if (userBean != null) {
//                                    try {
//                                        db.dropTable(UserBean.class);
//                                        db.save(userBean.getUser());
//                                        sendLoginSuccessBrodCast();
//
//                                        Toasty.success(LoginActivity.this, "登录成功").show();
//                                        Tool.setStringShared(context, "loginType", type);
//                                        Tool.setStringShared(context, "openId", openId);
//                                        //finish();
////                                loginTim(userBean.getUser().getTimIdentifier(), userBean.getUser().getTimSignature(),0);
////                                finish();
//                                    } catch (DbException e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            } else {
//                                showToast(bean.getMsg());
//                                Intent intent = new Intent(LoginActivity.this, LoginActivity.class);
//                                startActivity(intent);
//                            }
//
//                        } else {
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable ex, boolean isOnCallback) {
//                        MyLog.e(TAG, "http请求失败：" + ex.toString());
//                        dialogDismiss();
//                    }
//
//                    @Override
//                    public void onCancelled(Callback.CancelledException cex) {
//                        dialogDismiss();
//                    }
//
//                    @Override
//                    public void onFinished() {
//                        dialogDismiss();
//                    }
//                });
    }

    private void getUnionid(String token) {
//        if (!HttpUtil.isNetworkConnected(this)) {
//            Tool.goNoNetWork(context);
//            return;
//        }

        // TODO: 2018/7/18 下边的联网先注释掉
//        String url = "https://graph.qq.com/oauth2.0/me?access_token=" + token + "&unionid=1";
//        RequestParams params = new RequestParams(url);
//        x.http().get(params, new Callback.CommonCallback<String>() {
//            @Override
//            public void onSuccess(String result) {
//
//                result = result.replace("callback(", "");
//                result = result.replace(")", "");
//                MyLog.d(TAG, "请求成功" + result);
//                try {
//                    JSONObject ob = new JSONObject(result);
//                    if (ob.has("unionid")) {
//                        String unionid = ob.getString("unionid");
//                        thirdType = "qq";
//                        isExistUnionId(unionid, "user_qqopenid");
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onError(Throwable ex, boolean isOnCallback) {
//                MyLog.e(TAG, "http请求失败：" + ex.toString());
//                dialogDismiss();
//            }
//
//            @Override
//            public void onCancelled(CancelledException cex) {
//                dialogDismiss();
//            }
//
//            @Override
//            public void onFinished() {
//                dialogDismiss();
//            }
//        });
    }

    private void sendLoginSuccessBrodCast() {
        //开启广播
        //创建一个意图对象
        Intent intent = new Intent();
        //指定发送广播的频道
        intent.setAction("com.yitaohui.yitaogou");
        //发送广播的数据
        intent.putExtra("key", "loginSuccess");
        //发送
        sendBroadcast(intent);
    }

    private void closeKeyboard() {
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

//    @Override
//    public void showSuccessMsg(String s, LoginBean loginBean) {
////        Logger.d("showSuccessMsg" + s);
//        Toasty.success(this, s).show();
//        RxSPTool.putString(this, RxSPConfig.USER_PWD, mSPswEt);//密码
//        RxSPTool.putBoolean(this, RxSPConfig.IS_LOGIN, true);//是否登录
//        RxSPTool.putString(this, RxSPConfig.TOKEN, loginBean.getData().getToken());//用户token
//        RxSPTool.putString(this, RxSPConfig.USER_ID, loginBean.getData().getId());//用户ID
//        RxSPTool.putString(this, RxSPConfig.USER_NICKNAME, loginBean.getData().getNickname());//用户昵称
//        RxSPTool.putString(this, RxSPConfig.USER_PHONE, loginBean.getData().getPhone());//手机号
//        RxSPTool.putString(this, RxSPConfig.USER_AVATAR, loginBean.getData().getAvatar());//用户token
//        RxSPTool.putString(this, RxSPConfig.USER_TRUENAME, loginBean.getData().getTruename());//真实姓名
//        RxSPTool.putString(this, RxSPConfig.USER_NAME, loginBean.getData().getUsername());//用户名
//
//        ConfigBean configBean = new ConfigBean();
//        configBean.setToken(loginBean.getData().getToken());
//
//        Log.e("登录之后生成的token:", loginBean.getData().getToken() + "来了");
//
////        String login = new Gson().toJson(loginBean.getData());
////        RxSPTool.putJSONCache(this, RxSPConfig.LOGIN_DATABEAN, login);
//
//        finish();//登录成功关闭登录页面
//    }
//
//    @Override
//    public void showErrorMsg(String s) {
//        Toasty.error(this, s).show();
//    }


}
